package org.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.common.util.MailServiceUtil;
import org.example.dao.TbBankInfoDao;
import org.example.entity.TbBankInfoEntity;
import org.example.entity.bank.BankEntity;
import org.example.enums.OpenMethodEnums;
import org.example.exception.BizException;
import org.example.service.BankService;
import org.example.service.TbBankInfoService;
import org.example.vo.TbBankInfoVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class TbBankInfoServiceImpl extends ServiceImpl<TbBankInfoDao, TbBankInfoEntity> implements TbBankInfoService {

    @Resource
    private MailServiceUtil mailServiceUtil;


    @Resource
    private BankService bankService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBank(TbBankInfoVo tbBankInfoVo) {
        boolean flag=false;
        try {
            TbBankInfoEntity entity=new TbBankInfoEntity();
            BeanUtil.copyProperties(tbBankInfoVo,entity);
            flag = this.save(entity);
            StringBuffer sb =new StringBuffer();
            String bankName="";
            if(ObjectUtil.isNotNull(tbBankInfoVo.getBankId())){
                BankEntity bank = bankService.getById(tbBankInfoVo.getBankId());
                bankName=bank==null?null:bank.getName();
            }
            String openMethod="";
            if(StrUtil.isNotBlank(tbBankInfoVo.getOpenMethod())){
                openMethod= OpenMethodEnums.getEnums(tbBankInfoVo.getOpenMethod()).getName();
            }
            sb.append("姓名："+entity.getName()+"\\r\\n");
            sb.append("手机号："+entity.getMobile()+"\\r\\n");
            sb.append("地址："+entity.getAddress()+"\\r\\n");
            if(ObjectUtil.isNotNull(entity.getOpenTime())){
                sb.append("开户时间："+ DateUtil.format(entity.getOpenTime(), DatePattern.NORM_DATETIME_FORMAT) +"\\r\\n");
            }
            if(StrUtil.isNotBlank(openMethod)){
                sb.append("开户方式："+openMethod+"\\r\\n");
            }
            if(StrUtil.isNotBlank(bankName)){
                sb.append("开户银行："+bankName+"\\r\\n");
            }
            if(flag){
                new Thread(()->{
                    mailServiceUtil.sendMail("用户注册",sb.toString());
                }).start();
            }
        }catch (Exception e){
            log.error("异常",e);
            throw new BizException("新增开户报错");
        }
        return flag;
    }
}
